<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <el-button
            class="button"
            type="primary"
            :icon="Plus"
            @click="addTrademarkInfo"
            >添加</el-button
          >
        </div>
      </template>
      <!-- 表格 -->
      <el-table :data="trademarkList" style="width: 100%">
        <el-table-column label="序号" align="center" type="index" width="80" />
        <el-table-column
          label="品牌名称"
          width="300"
          align="center"
          property="tmName"
        />
        <el-table-column
          label="品牌LOGO"
          width="300"
          align="center"
          property="logoUrl"
        >
          <template #default="{ row, $index }">
            <img :src="row.logoUrl" style="width: 80px; height: 80px" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row, $index }">
            <el-button type="warning" :icon="Edit" @click="updateSave(row)"
              >编辑</el-button
            >
            <el-button type="danger" :icon="Delete" @click="deleteSave(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
        >
      </el-table>
      <!-- 页码-》分页 -->
      <el-pagination
        style="margin-top: 18px"
        v-model:currentPage="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 6, 9]"
        layout=" prev, pager, next,jumper,->,sizes,total"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 点击弹出表单进行添加 -->
    <el-dialog
      v-model="dialogFormVisible"
      v-model:title="dialogTitle"
      @close="onCancelSave(tmFormRef)"
    >
      <el-form
        :model="tmForm"
        :rules="rules"
        ref="tmFormRef"
        style="width: 500px"
        label-width="100px"
      >
        <el-form-item label="品牌名称" :label-width="100" prop="tmName">
          <el-input v-model="tmForm.tmName" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌LOGO" :label-width="100" prop="logoUrl">
          <!--   handleAvatarSuccess请求成功的回调    beforeAvatarUpload获取前作的一些判断回调  -->
          <el-upload
            class="avatar-uploader"
            action="/app-dev/admin/product/upload"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">上传图片必须是jpg且不能大于2M</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancelSave(tmFormRef)">取消</el-button>
          <el-button type="primary" @click="onSave(tmFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import type { TrademarkListModel, TrademarkModel } from "@/api/trademark";
import TrademarkApi from "@/api/trademark";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
  type UploadProps,
} from "element-plus";
//设置图标的样式
import { Delete, Edit, Plus } from "@element-plus/icons-vue";

let trademarkList = ref<TrademarkListModel>();
//分页信息
const currentPage = ref(1);
const pageSize = ref(3);
const total = ref(0);

const tmFormRef = ref<FormInstance>();
//控制开关
const dialogFormVisible = ref<boolean>(false);
const tmForm = ref<TrademarkModel>({
  id: -1,
  tmName: "",
  logoUrl: "",
});
//点击添加触发的回调
const addTrademarkInfo = () => {
  dialogFormVisible.value = true;
  dialogTitle.value = "添加商品";
};
//发送请求获取数据
onMounted(() => {
  //页面初始化就发送数据
  getPage();
});
//封装获取用户请求
const getPage = async (page = currentPage.value) => {
  try {
    let result = await TrademarkApi.getPage(page, pageSize.value);
    trademarkList.value = result.records; // 给表格数据赋值
    total.value = result.total; // 总条数
  } catch (e) {
    ElMessage.error("获取品牌分页数据失败");
  }
};

//控制每页显示多少条数据
const handleSizeChange = async (val: number) => {
  //修改每页显示条数 重新发送请求调用getPage方法 修改一下
  pageSize.value = val;
  currentPage.value = 1;
  await getPage(1);
};
//控制显示第几页
const handleCurrentChange = async (val: number) => {
  currentPage.value = val;
  await getPage();
};

//表单信息
//弹出取消表单回调
// const onCancelSave = () => {
//   dialogFormVisible.value = false;
// };
// //弹出确认表单回调
// const onSave = () => {
//   dialogFormVisible.value = false;
// };

//发送图片请求
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  if (response) {
    tmForm.value.logoUrl = response.data;
  } else {
    ElMessage.error("发送图片请求失败");
  }
};
//获取图片前的处理进行判断  图片是否合理
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("上传的图片必须为jpg格式");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("上传图片的大小不能超过2MB!");
    return false;
  }

  return true;
};

//表单校验
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "请输入你的品牌名称", trigger: "blur" },
    { min: 2, message: "品牌名称的字符串一定大于1", trigger: "blur" },
  ],
  logoUrl: [{ required: true, message: "需要上传你的图片", trigger: "change" }],
});
//弹出确认表单回调
const onSave = async (formEl: FormInstance | undefined) => {
  console.log(formEl);
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // console.log('submit!')
      //通过校验发送数据
      //对id进行判断 如果id大于0则是修改请求  是-1则是添加请求
      const tmId = tmForm.value.id as number;
      console.log(tmId);
      console.log(tmForm.value);
      if (tmId > 0) {
        try {
          //修改数据的请求
          await TrademarkApi.update(tmForm.value);
          ElMessage.success("修改商品成功");
          //重新获取数据发送请求 响应新的数据
          await getPage();
        } catch (error: any) {
          ElMessage.info("修改商品失败");
          return Promise.reject(new Error("修改商品失败"));
        }
      } else {
        try {
          //添加数据的请求
          const { tmName, logoUrl } = tmForm.value;
          await TrademarkApi.add({ tmName, logoUrl });
          ElMessage.success("添加商品成功");
          //重新获取数据发送请求 响应新的数据 跳转到第一页
          currentPage.value = 1;
          await getPage(1);
        } catch (e) {
          ElMessage.info("添加商品失败");
          return Promise.reject(new Error("添加商品失败"));
        }
      }
      dialogFormVisible.value = false;
    } else {
      console.log("error submit!", fields);
    }
  });
};
//弹出取消表单回调
const onCancelSave = (formEl: FormInstance) => {
  //点击取消时 清空表单 并且取消表单验证
  formEl.resetFields();
  tmForm.value.logoUrl = "";
  tmForm.value.tmName = "";
  tmForm.value.id = -1;
  dialogFormVisible.value = false;
};
//针对点击的是添加还是修改对标题进行不同的显示
let dialogTitle = ref<string>("");
//修改数据
const updateSave = (row: any) => {
  dialogTitle.value = "修改品牌";
  console.log(row);
  dialogFormVisible.value = true;
  const { id, logoUrl, tmName } = row;
  tmForm.value.id = id;
  tmForm.value.logoUrl = logoUrl;
  tmForm.value.tmName = tmName;
};
//删除商品的信息
const deleteSave = (row: any) => {
  const tmId = row.id;
  //删除的时候如果是最后一条数据表 需要跳转到上一页的数据
  if (trademarkList.value?.length === 1 && currentPage.value != 1) {
    currentPage.value -= 1;
  }
  ElMessageBox.confirm(`你确定删除${row.tmName}商品吗？`, "删除商品", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await TrademarkApi.delete(tmId as number);
        ElMessage.success("删除成功");
        await getPage();
      } catch (e) {
        return Promise.reject(new Error("失败"));
      }
    })
    .catch((e) => {
      if (typeof e === "object") {
        ElMessage.error("删除商品失败");
      } else {
        ElMessage.info("取消删除");
      }
    });
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
